package com.br.semperparata.components.gui;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import javax.swing.SpinnerListModel;
import javax.swing.SpinnerModel;

public class MinuteSpinnerModel  extends SpinnerListModel {
	private static final long serialVersionUID = 1L;
	private Date firstValue, lastValue;
    private SpinnerModel linkedModel = null;
    private DateFormat dateFormat;
    
    protected MinuteSpinnerModel(int duaration, int increment) {
    	super();
    	
    	dateFormat = new SimpleDateFormat("HH:mm");
    	
    	Calendar cal = Calendar.getInstance();
    	cal.set(Calendar.HOUR_OF_DAY, 0);
    	cal.set(Calendar.MINUTE, 0);
    	cal.set(Calendar.SECOND, 0);
		
		ArrayList<Date> list = new ArrayList<Date>();
		for (int min = 0; min <= duaration; min += increment) {
			Calendar c = (Calendar)cal.clone();
			c.add(Calendar.MINUTE, min);
			list.add(c.getTime());
		}
		if (list.size() > 0) {
			this.firstValue = list.get(0);
	    	this.lastValue = list.get(list.size() - 1);
		}
    	this.setList(list);
    }

    public void setLinkedModel(SpinnerModel linkedModel) {
        this.linkedModel = linkedModel;
    }
    
    @Override
    public String getValue() {
        Date value = (Date)super.getValue();
        if (value == null)
            value = firstValue;
        return dateFormat.format(value);
    }

    @Override
    public Date getNextValue() {
        Date value = (Date)super.getNextValue();
        if (value == null) {
            value = firstValue;
            if (linkedModel != null) {
                linkedModel.setValue(linkedModel.getNextValue());
            }
        }
        return value;
    }

    @Override
    public Date getPreviousValue() {
    	Date value = (Date)super.getPreviousValue();
        if (value == null) {
            value = lastValue;
            if (linkedModel != null) {
                linkedModel.setValue(linkedModel.getPreviousValue());
            }
        }
        return value;
    }
}